/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.library.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.library.common.base.ApiResult;
import com.library.entity.BookExposureEntity;
import com.library.entity.BookTypeEntity;
import com.library.entity.vo.BookResourceVo;
import com.library.mapper.BookTypeMapper;
import com.library.service.BookDataTypeService;
import com.library.service.BookTypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 中图法分类表
 *
 * @author pig
 * @date 2023-09-26 09:27:21
 */
@Slf4j
@Service
public class BookTypeServiceImpl extends ServiceImpl<BookTypeMapper, BookTypeEntity> implements BookTypeService {

    @Resource
    private BookDataTypeService bookDataTypeService;

    //@Value("${digitallibrary.httpIp}")
    private String httpIp;

    //@Value("${digitallibrary.username}")
    private String username;

    //@Value("${digitallibrary.password}")
    private String password;

    @Override
    public ApiResult synchronization() {
        try {
            String token = selectToken(httpIp + "/auth/oauth2/token");
            ObjectMapper objectMapper = new ObjectMapper();
            BookExposureEntity bookExposureEntity = new BookExposureEntity();
            bookExposureEntity.setUsername(username);
            bookExposureEntity.setPassword(password);
            String json = objectMapper.writeValueAsString(bookExposureEntity);
            String jsonString =resourceType(token, httpIp + "/digitallibrary/bookExposure/getBookType", json);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            JSONArray dataArray = jsonObject.getJSONArray("data");
            LambdaQueryWrapper<BookTypeEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(BookTypeEntity::getType,"0");
            this.remove(wrapper);
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject dataObject = dataArray.getJSONObject(i);
                BookTypeEntity bookType = new BookTypeEntity();
                String id = dataObject.getString("id");
                bookType.setId(Long.valueOf(id));
                bookType.setBookType(dataObject.getString("bookType"));
                bookType.setTypeName(dataObject.getString("typeName"));
                bookType.setDataTypeStatus(dataObject.getString("dataTypeStatus"));
                String id1 = dataObject.getString("datatypeId");
                bookType.setDatatypeId(Long.valueOf(id1));
                bookType.setType("0");
                this.save(bookType);
            }
            return ApiResult.ok("同步成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String selectToken(String pathUrl) {
        String result = "";
        String data = "";
        String username = "jkuser";
        String password = "JFat0Zdc";
        String scope = "server";

        try {
            URL url = new URL(pathUrl);

            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            //设定请求的方法为"POST"，默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
            conn.setRequestMethod("POST");

            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);

            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在http正文内，因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            conn.setDoInput(true);

            // Post请求不能使用缓存
            conn.setUseCaches(false);

            //设置通用的请求属性
            conn.setRequestProperty("skipToken", "true");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            // 添加基本身份验证
            conn.setRequestProperty("Authorization", "Basic dGVzdDp0ZXN0");

            String encodedParams = "username=" + URLEncoder.encode(username, String.valueOf(StandardCharsets.UTF_8)) +
                    "&password=" + URLEncoder.encode(password, String.valueOf(StandardCharsets.UTF_8)) +
                    "&scope=" + URLEncoder.encode(scope, String.valueOf(StandardCharsets.UTF_8)) +
                    "&grant_type=" + URLEncoder.encode("password", String.valueOf(StandardCharsets.UTF_8));

            conn.getOutputStream().write(encodedParams.getBytes());

            //连接，从上述url.openConnection()至此的配置必须要在connect之前完成，
            int code = conn.getResponseCode();//获得响应码
            if (code == 200) {//响应成功，获得响应的数据

                //解决中文乱码
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                //解决返回参数换行问题，一次读一行，读入null时文件结束
                int line = 1;
                String tempString = null;
                while ((tempString = reader.readLine()) != null) {
                    result += tempString;
                    //把当前行号显示出来
                    //System.out.println("line " + line + ": " + tempString);
                    line++;
                }
                reader.close();

            }
            conn.disconnect();   //断开连接


            ObjectMapper objectMapper = new ObjectMapper();

            JsonNode rootNode = objectMapper.readTree(result);

            String tokenType = rootNode.get("token_type").asText();
            String accessToken = rootNode.get("access_token").asText();
            log.info("JsonNode:" + rootNode);
            data = tokenType + ' ' + accessToken;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return data;
    }
    public static String resourceType(String Authorization, String httpUrl, String requestData) {
        String responseData = "";
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            if (Authorization != null){
                connection.setRequestProperty("Authorization", Authorization);
            }


            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(requestData.getBytes("UTF-8"));

            outputStream.flush();
            outputStream.close();

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) { // 响应成功，获取响应数据

                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

                String tempString;
                while ((tempString = reader.readLine()) != null) {
                    responseData += tempString;
                }
                reader.close();
            }

            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseData;
    }


}
